package com.project.genesis.common.util;

import com.project.genesis.common.exception.MyException;
import com.project.genesis.common.result.ResultCodeEnum;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MQSendUtils implements RabbitTemplate.ConfirmCallback{

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    public MQSendUtils(RabbitTemplate rabbitTemplate){
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setConfirmCallback(this::confirm);
    }

    public void sendMsg(String exchangeName, String routingKey, String msg, int second){
        rabbitTemplate.convertAndSend(exchangeName, routingKey, msg, correlationData -> {
            correlationData.getMessageProperties().setDelay(second);
            return correlationData;
        });
    }


    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (!ack){
            throw new MyException(ResultCodeEnum.PUSH_ERROR);
        }
    }
}
